给定一个逆波兰表达式,求表达式的值。
数据范围:表达式长度满足 ,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足 。
class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here stack = [] for i in tokens: stack.append(i) if(stack[-1] in ['+','-','*','/']): operator = stack.pop() right = stack.pop() left = stack.pop() stack.append(str(int(eval(left+operator+right)))) return int(stack[0])
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> stk; int tmp1, tmp2; for (auto i : tokens) if (i[0] < 48 && i.size() == 1) { tmp1 = stk.top(); stk.pop(); tmp2 = stk.top(); stk.pop(); if (i[0] == 42) stk.push(tmp2 * tmp1); else if (i[0] == 43) stk.push(tmp2 + tmp1); else if (i[0] == 45) stk.push(tmp2 - tmp1); else stk.push(tmp2 / tmp1); } else stk.push(stoi(i)); return stk.top(); } };
class Solution: def evalRPN(self , tokens: List[str]) -> int: stk = [] for i in tokens: if ord(i[-1]) < 48: tmp = stk.pop() stk.append(str(int(eval((stk.pop() + i + tmp))))) else: stk.append(i) return int(stk[-1])
class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here if len(tokens) == 1: return int(tokens[0]) l = [] x = 0 y = 0 for i in tokens: if i not in '+-*/': l.append(i) else: x = l.pop() y = l.pop() # 一定要转为int res = int(eval(str(y) + str(i) + str(x))) l.append(res) return l[0]
class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here stack = [] for token in tokens: if token == '+': stack.append(stack.pop()+stack.pop()) elif token == '-': stack.append(-stack.pop()+stack.pop()) elif token == '*': stack.append(stack.pop()*stack.pop()) elif token == '/': stack.append(int(1/stack.pop()*stack.pop())) else: stack.append(int(token)) return stack.pop()
num = [] caozuodict = {'+', '-', '*', '/'} for item in tokens: if item in caozuodict: a = num.pop() b = num.pop() if item == '+': num.append(a+b) elif item == '-': num.append(b-a) elif item == '*': num.append(a*b) else: num.append(int(b/a)) else: num.append(int(item)) print(num[0])
class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here ls = [] for i in range(len(tokens)): if tokens[i] in ["+","-","*","/"]: l1 = ls.pop() l2 = ls.pop() res = str(int(eval(l2 + tokens[i] + l1))) ls.append(res) else: ls.append(tokens[i]) return int(ls[-1])